/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.tcc.builtinimpls;

import com.inspur.edp.bef.spi.action.tcc.BefTccHandler;
import com.inspur.edp.cdf.component.api.service.ComponentInvokeService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

public class BefTccHandlerAssembler {

  private List<BefTccHandler> handlers;
  private List<String> handlerIds;
  private List<String> handlerNames;
  private List<BefTccHandler> childHandlers;
  private String nodeCode;

  public List<BefTccHandler> getHandlers() {
    if (handlers == null && handlerIds != null) {
      ComponentInvokeService compService = SpringBeanUtils.getBean(ComponentInvokeService.class);

      handlers = new ArrayList<>(handlerIds.size());
      for (int i = 0; i < handlerIds.size(); ++i) {
        try {
          handlers.add((BefTccHandler) compService.getInstance(handlerIds.get(i)));
        } catch (NoSuchBeanDefinitionException e) {
          throw new RuntimeException(String
              .format("业务实体的对象[%s]上的tcc配置项[%s]的构件创建失败, 请参考通用构件相关文档正确注册构件", getNodeCode(),
                  handlerNames.get(i)), e);
        }
      }
    }
    return handlers;
  }

  public void addHandler(String name, String id) {
    Objects.requireNonNull(id);

    if (handlerIds == null) {
      handlerIds = new ArrayList<>();
      handlerNames = new ArrayList<>();
    }
    handlerNames.add(name);
    handlerIds.add(id);
  }

  public List<BefTccHandler> getChildAssemblers() {
    return childHandlers == null ? Collections.emptyList() : childHandlers;
  }

  public void addChildHandler(BefTccHandler handler) {
    if (childHandlers == null) {
      childHandlers = new ArrayList<>();
    }
    childHandlers.add(handler);
  }

  public String getNodeCode() {
    return nodeCode;
  }

  public void setNodeCode(String nodeCode) {
    this.nodeCode = nodeCode;
  }
}
